module GeneratorExtension
  module Create
    module InstanceMethods
    def route_resources_in_namespace (resource, namespaces)
      sentinel = 'ActionController::Routing::Routes.draw do |map|'
      tab = "  "
      result =""
      logger.route "namespaces: #{namespaces}, map.resources #{resource}"
      unless options[:pretend]
        gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
          if namespaces.is_a?(Array)
            result << "\n#{tab}map.namespace :#{namespaces[0]} do |#{namespaces[0]}|"
            if namespaces.length > 1 
              indent = 2
              last_namespace = namespaces[0]
              namespaces[1..namespaces.length-1].each do |namespace|
                result << "\n#{tab*indent}#{last_namespace}.namespace :#{namespace} do |#{namespace}|"
                indent+=1
                last_namespace=namespace
              end
              result << "\n#{tab*(indent+1)}#{last_namespace}.resources :#{resource}"
              [1..namespaces.length-1].each do |index|
                result << "\n#{tab*indent}end"
                indent -=1
              end
            end
            result << "\nend"
          else
            result << "\n#{tab}map.namespace :#{namespaces} do |#{namespaces}|"
            result << "\n#{tab}#{tab} #{namespaces}.resources :#{resource}"
            result << "\n#{tab}end"
          end
          "#{match}\n#{result}"
        end
      end
    end
  end
  end
  module Destroy
    module InstanceMethods
      def route_resources_in_namespace(resource, namespaces)
        ## ignore for now
      end
    end
  end
end

Rails::Generator::Commands::Create.send(:include, GeneratorExtension::Create::InstanceMethods)
Rails::Generator::Commands::Destroy.send(:include, GeneratorExtension::Destroy::InstanceMethods)